﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace System
{
    /// <summary>
    /// Extension methods for String class.
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// 设定一个长度，然后若字符串不足指定长度的话，就用空补足，若超出长度的话则截取指定长度。
        /// </summary>
        /// <param name="str"></param>
        /// <param name="width">指定长度</param>
        /// <param name="font">字体设定</param>
        /// <returns></returns>
        public static string Pad(this string str, int width, Font font)
        {
            if (str == null)
                throw new ArgumentNullException(nameof(str));

            if (width < 0)
                throw new ArgumentOutOfRangeException(nameof(width), "Length must be non-negative.");

            if (font == null)
                throw new ArgumentNullException(nameof(font));

            int textWidth = (int)TextRenderer.MeasureText(str, font).Width;
            if (textWidth == width)
                return str;

            string desString;
            int stringLength = str.Length;
            while (true)
            {
                desString = str.PadRight(stringLength);
                textWidth = (int)TextRenderer.MeasureText(desString, font).Width;
                if (textWidth >= width)
                {
                    break;
                }

                stringLength++;
            }

            return desString;
        }
    }
}
